package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.esport.MyPredictionContract
import com.cqhz.quwan.mvp.esport.MyPredictionPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.formatMoney
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_my_prediction.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject

/**
 * 我的预测
 * Created by Guojing on 2018/10/12.
 */
class MyPredictionActivity : GoBackActivity(), MyPredictionContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var modelHelper: ModelHelper
    @Inject
    lateinit var myPredictionPresenter: MyPredictionPresenter
    private var loginBean: LoginBean? = null
    private var titles = arrayOf("竞猜记录", "中奖记录")
    private var type: Int = 0// type 0:竞猜记录 1:中奖记录
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var orders = ArrayList<ArrayList<ESportOrderItemBean>>()

    override fun layout(): Int {
        return R.layout.activity_my_prediction
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "我的预测"
    }

    override fun initView() {
        loginBean = APP.get()!!.loginInfo
        myPredictionPresenter.attachView(this)

        if (!StringUtils.isEmpty(loginBean!!.userId)) {
            myPredictionPresenter.getUserInfo(loginBean!!.userId!!)
        }
        // 初始化页面元素和相应数据以及适配器
        for (i in 1..titles.size) {
            initAdapter()
        }
        initPager()
        // 加载数据
        refreshCurrentPage()
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var orderList = ArrayList<ESportOrderItemBean>()
        var orderListAdapter = CommonAdapterHelper.getGuessListAdapter(orderList)
        orderListAdapter.emptyView = emptyView

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.adapter = orderListAdapter
        orderListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (orders[currentPage].size > 0) {
                if (orders[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = orders[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    myPredictionPresenter.getOrderList(loginBean!!.userId!!, currentPage, pageNo, KeyContract.pageSize)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                myPredictionPresenter.getOrderList(loginBean!!.userId!!, currentPage, 1, KeyContract.pageSize)
            }
        }, holder.rvContent)
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as ESportOrderItemBean

                val intent = Intent(context(), ESportOrderDetailActivity::class.java)
                intent.putExtra(KeyContract.OrderId,item.id)
                startActivity(intent)
            }
        })
        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        orders.add(orderList)
        adapters.add(orderListAdapter)
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (orders[position].size <= 0) {
                    refreshCurrentPage()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    override fun setGuessStatistics(userInfoBean: UserInfoBean) {

    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        var currentPage = vp_content.currentItem
        myPredictionPresenter.getOrderList(loginBean!!.userId!!, currentPage, 1, KeyContract.pageSize)
    }

    override fun loadOrderList(currentPage: Int, pageNo: Int, bean: ESportOrderResultBean) {
        tv_guess_number.text = bean.competitionNumber
        tv_winning_probability.text = (bean.winnProbability.toDouble() * 100).toString().formatMoney() + "%"
        tv_total_income.text = bean.totalIncome

        if (pageNo == 1) {
            orders[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader!!) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (bean.page.records.isNotEmpty()) {
            orders[currentPage].addAll(bean.page.records)
        }

        if (bean.page.total > orders[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onResume() {
        super.onResume()

        if (loginBean != null && !StringUtils.isEmpty(loginBean!!.userId)) {
            myPredictionPresenter.getUserInfo(loginBean!!.userId!!)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        myPredictionPresenter.detachView()
    }
}
